<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/
namespace app\hgapi\controller;
use app\admin\model\user\UserTrade;
use app\hgapi\model\market\MarketBack;
use app\hgapi\model\market\MarketBargain;
use app\hgapi\model\market\MarketLikes;
use app\hgapi\model\market\MarketPurchase;
use app\hgapi\model\market\MarketSeckill;
use app\hgapi\model\market\MarketSeckillTime;
use app\hgapi\model\market\MarketSpell;
use app\hgapi\model\store\StoreOrder;
use app\hgapi\model\store\StoreProduct;
use app\hgapi\model\store\StoreProductCoupon;
use app\hgapi\model\system\ContentPage;
use app\hgapi\model\system\PopupRecord;
use app\hgapi\model\user\UserCarry;
use app\hgapi\model\user\UserChoose;
use app\hgapi\model\user\UserLead;
use app\hgapi\model\user\UserRole;
use app\hgapi\model\user\User;
use app\hgapi\model\goods\GoodsGiftCode;
use app\hgapi\model\goods\GoodsGift;
use app\hgapi\model\goods\GoodsPackage;

class SystemApi extends Auth{

    /**
     * 获取审核信息
     */
    public function huokeHe(){
        $start = input('start');
        $limit = input('limit');
        $info = input('info');
        $name = base64_encode($info);
        $status = input('status');
        if ($status != ''){
            $where['status'] = $status;
        }
        $nameId = User::getField(['name' => ['like', "%$name%"]], 'id', 1);
        $list = UserCarry::selCarryZhi($where, $info, $nameId, $start, $limit);
        successCode(['count' => $list['count'], 'data' => $list['data']]);
    }

    /**
     * 图片上传
     */
    public function uploads(){
        upload('lipin');
    }

    /**
     * 礼品商家审核
     */
    public function provide_shenhe(){
        $field = json_decode(input()['field'], true);
        $id = $field['id']; //当前申请id
        $recruit = $field['recruit']; //招商人
        $phone = $field['phone']; //商家手机号
        $uid = $field['uid']; //商家
        $name = $field['name']; //商家名称
        $latitude = $field['latitude']; //纬度
        $longitude = $field['longitude']; //经度
        $address = $field['address']; //地址
        if (!$uid){
            echo json_encode(array('info' => 0, 'msg' => '数据错误'));
            exit;
        }
        //添加商家信息
        $data = [
            'uid' => $uid,
            'name' => $name,
            'address' => $address,
            'latitude' => $latitude,
            'longitude' => $longitude,
        ];
        $re = UserTrade::add($data);
        //成功后申请数据的状态
        if ($re){
            //修改当前商家的账户属性和上级招商员
            User::edit(['id' => $uid], ['recruit' => $recruit, 'phone' => $phone]);
            UserRole::upField($uid, 'gift', 1);
            //修改当前审核状态
            UserCarry::upField(['id' => $id], 'status', 1);
            successCode('审核成功');
        }else{
            errorCode('审核失败');
        }
    }

    /**
     * 拒绝通过
     */
    public function provide_jujue(){
        $id = input('id');
        if (!$id) errorCode('数据错误');
        $re = UserCarry::upField(['id' => $id], 'status', 2);
        if ($re){
            successCode('拒绝成功');
        }else{
            errorCode('拒绝失败');
        }
    }

    /**
     * 引流商家
     */
    public function cuHe(){
        $start = input('start');
        $limit = input('limit');
        $info = input('info');
        $name = base64_encode($info);
        $status = input('status');
        if ($status != ''){
            $where['status'] = $status;
        }
        $nameId = User::getField(['name' => ['like', "%$name%"]], 'id', 1);
        $list = UserLead::selLeadZhi($where, $info, $nameId, $start, $limit);
        successCode(['count' => $list['count'], 'data' => $list['data']]);
    }

    /**
     * 引流商家审核
     */
    public function drainage_shenhe(){
        $id = input('id');
        $type = input('type');
        $find = UserLead::getLead(['id' => $id], '');
        if ($find){
            if ($type == 1){
                $re = UserLead::upField(['id' => $id], 'status', 1);
                $data = [
                    'recruit' => $find['recruit'],
                    'phone' => $find['phone'],
                ];
                User::upUserInfo(['id' => $find['uid']], $data);
                UserRole::upField($find['uid'], 'drainage', 1);
                $img = $this->package_img($find['package'], $find['uid']);
                $add = [
                    'uid' => $find['uid'],
                    'package' => $find['package'],
                    'img' => $img
                ];
                UserChoose::add($add);
            }else{
                $re = UserLead::upField(['id' => $id], 'status', 2);
            }
            if ($re){
                successCode($type == 1 ? '通过成功' : '拒绝成功');
            }else{
                errorCode($type == 1 ? '通过失败' : '拒绝失败');
            }
        }else{
            errorCode('数据错误');
        }
    }

    /**
     * 获取我的大礼包二维码
     * @param $id
     * @param $uid
     * @return string
     */
    public function package_img($id, $uid){
        $access_token = access_token();
        $scene = "page:9,page_id:$id,yid:$uid";
        $img = createImg($access_token, $scene);
        $name = $id.'-'.time().'-'.$uid;
        file_put_contents('uploads/package/code-'.$name.'.png', $img);
        //存储二维码路径
        $img_url = 'uploads/package/code-'.$name.'.png';
        return $img_url;
    }

    /**
     * 图片上传
     */
    public function uploads2(){
        upload('package');
    }

    /**
     * 大礼包添加
     */
    public function package_add(){
        $field = json_decode(input()['field'], true);
        $name = $field['name']; //大礼包名称
        $date = explode(' - ', $field['date']); //日期
        $start = strtotime($date[0]); //开始日期 转换为时间戳
        $end = strtotime($date[1]); //结束日期 转换为时间戳
        $sort = $field['sort']; //排序
        $img = $field['img']; //大礼包封面
        $gid = $field['gid']; //选择的礼品 ,隔开
        $money = $field['money']; //需要支付金额
        $type = $field['type']; //领取状态
        $uid = $field['uid'];
        //添加大礼包
        $data = [
            'name' => $name,
            'start' => $start,
            'end' => $end,
            'sort' => $sort,
            'gid' => $gid,
            'img' => $img,
            'money' => $money,
            'type' => $type,
            'zid' => $uid,
            'status' => $uid == 0 ? 1 : 0,
        ];
        $re = GoodsPackage::add($data);
        if ($re){
            successCode('添加成功');
        }else{
            errorCode('添加失败');
        }
    }

    /**
     * 查询所有礼品
     */
    public function gift(){
        $uid = input('uid');
        if ($uid){
            $list1 = GoodsGift::selGift(['status' => 1, 'uid' => $uid]);
            $list2 = GoodsGift::selGift(['status' => 1, 'is_zu' => 1, 'uid' => ['neq', $uid]]);
            if ($list1) $list1 = $list1->toArray();
            if ($list2) $list2 = $list2->toArray();
            $list = array_merge($list1, $list2);
        }else{
            $list = GoodsGift::selGift(['status' => 1, 'is_zu' => 1]);
        }
        foreach ($list as $k => $v){
            $name = User::getField(['id' => $v['uid']], 'name', 0);
            $list[$k]['name'] = base64_decode($name);
        }
        successCode($list);
    }

    /**
     * 礼品管理
     */
    public function lpgl(){
        $start = input('start');
        $limit = input('limit');
        $data = GoodsGift::selGiftLimit($start, $limit);
        foreach ($data as $k => $v){
            $find = User::getUserInfo(['id' => $v['uid']], 'name, phone');;
            $name = base64_decode($find['name']);
            $phone = '('.$find['phone'].')';
            $data[$k]['name'] = $v['uid'] ? $name.$phone : '平台';
            //查询当前礼品是否已经生成核销码
            $is = GoodsGiftCode::getCodeInfo(['lid' => $v['id']]);
            $data[$k]['is'] = $is ? 1 : 0;
        }
        $count = GoodsGift::countGift('');
        successCode(['count' => $count, 'data' => $data]);
    }

    /**
     * 礼品审核
     */
    public function gift_shenhe(){
        $field = json_decode(input()['field'], true);
        $id = $field['id']; //当前申请id
        $uid = $field['uid']; //商家
        $latitude = $field['latitude']; //纬度
        $longitude = $field['longitude']; //经度
        $address = $field['address']; //地址
        $lipin = $field['lipin']; //礼品名称
        $img = $field['img']; //礼品封面
        $num = $field['num']; //礼品数量
        $stage = $field['stage']; //分期
        $mode = $field['mode']; //领取方式
        $money = $field['money']; //需要消费金额
        $price = $field['price']; //礼品价值
        $ge = $field['ge']; //每期间隔天数
        $gold = $field['gold']; //佣金
        if (!$uid) errorCode('数据错误');
        if (!$lipin) errorCode('请输入礼品名称');
        if (!$img) errorCode('请上传礼品封面');
        if (!$num) errorCode('请输入礼品数量');
        //添加商家信息
        $data = [
            'uid' => $uid,
            'address' => $address,
            'latitude' => $latitude,
            'longitude' => $longitude,
            'lipin' => $lipin,
            'img' => $img,
            'num' => $num,
            'stage' => $stage,
            'mode' => $mode,
            'money' => $money,
            'price' => $price,
            'ge' => $ge,
            'gold' => $gold,
            'status' => 1
        ];
        $re = GoodsGift::edit(['id' => $id], $data);
        //成功后申请数据的状态
        if ($re){
            $this->create($id);
            successCode('审核成功');
        }else{
            errorCode('审核失败');
        }
    }

    /**
     * 拒绝通过
     */
    public function gift_jujue(){
        $id = input('id');
        if (!$id) errorCode('数据错误');
        $re = GoodsGift::upField(['id' => $id], 'status', 2);
        if ($re){
            successCode('拒绝成功');
        }else{
            errorCode('拒绝失败');
        }
    }

    /**
     * 生成核销码
     */
    public function create($id){
        //查出当前大礼包总个数
        $ge = GoodsGift::getGift(['id' => $id]);
        $num = $ge['num'];
        $stage = $ge['stage'];
        $whole = $num * $stage;
        if (!$num){ //如果数量错误就添加失败
            echo 1;
            exit;
        }
        //添加code码
        GoodsGiftCode::trans($whole, $num, $id);
    }

    /**
     * 获取页面信息
     */
    public function get_page(){
        $id = input('id');
        $uid = input('uid');
        $find = ContentPage::getPageInfo(['id' => $id]);
        if (!$find) errorCode('页面不存在');
        $popup = PopupRecord::getPopupRecordInfo(['uid' => $uid, 'popup' => $find['browse_popup_page']]);
        successCode(['data' => $find, 'popup' => $popup]);
    }

    /**
     * 获取页面数据
     */
    public function get_page_list(){
        $type = input('type');
        $num = input('num');
        $coupon = input('coupon');
        $start = input('start');
        $limit = input('limit');
        $shop = input('shop');
        $uid = input('uid');
        $time = time();
        if ($start > $num) errorCode('最多查询' . $num . '条数据');
        if ($start < $num && ($start + $limit) > $num){ //起始页条数小于总数和结束条数大于总数时
            $limit = $num - $start; //显示条数减去起始条数
        }
        switch ($type){
            case 1:
                $ids = StoreOrder::getField(['uid' => $uid, 'status' => 1, 'type' => 2], 'bargain_id');
                $hand = MarketBargain::selBargain(['id' => ['in', $ids], 'start_time' => ['elt', $time], 'end_time' => ['egt', $time], 'status' => 1]);
                $list = MarketBargain::selBargainLimit(['id' => ['not in', $ids], 'start_time' => ['elt', $time], 'end_time' => ['egt', $time], 'status' => 1], $start, $limit);
                successCode(compact('hand', 'list'));
                break;
            case 2:
                $ids = StoreOrder::getField(['uid' => $uid, 'status' => 1, 'type' => 3], 'spell_id');
                $hand = MarketSpell::selSpell(['id' => ['in', $ids], 'start_time' => ['elt', $time], 'end_time' => ['egt', $time], 'status' => 1]);
                $list = MarketSpell::selSpellLimit(['id' => ['not in', $ids], 'start_time' => ['elt', $time], 'end_time' => ['egt', $time], 'status' => 1], $start, $limit);
                successCode(compact('hand', 'list'));
                break;
            case 4:
                $ids = StoreOrder::getField(['uid' => $uid, 'status' => 1, 'type' => 5], 'back_id');
                $hand = MarketBack::selBack(['id' => ['in', $ids], 'status' => 1]);
                $list = MarketBack::selBackLimit(['id' => ['not in', $ids], 'status' => 1], $start, $limit);
                successCode(compact('hand', 'list'));
                break;
            case 5:
                $ids = StoreOrder::getField(['uid' => $uid, 'status' => 1, 'type' => 6], 'purchase_id');
                $hand = MarketPurchase::selPurchase(['id' => ['in', $ids], 'status' => 1]);
                $list = MarketPurchase::selPurchaseLimit(['id' => ['not in', $ids], 'status' => 1], $start, $limit);
                successCode(compact('hand', 'list'));
                break;
            case 6:
                $ids = StoreOrder::getField(['uid' => $uid, 'status' => 1, 'type' => 7], 'likes_id');
                $hand = MarketLikes::selLikes(['id' => ['in', $ids], 'start_time' => ['elt', $time], 'end_time' => ['egt', $time], 'status' => 1]);
                $list = MarketLikes::selLikesLimit(['id' => ['not in', $ids], 'start_time' => ['elt', $time], 'end_time' => ['egt', $time], 'status' => 1], $start, $limit);
                successCode(compact('hand', 'list'));
                break;
            case 7:
                $coupon_info = StoreProductCoupon::getCoupon(['id' => $coupon], '');
                if ($coupon_info['apply'] == 0){
                    $list = StoreProduct::selProductLimit(['status' => 0, 'is_del' => 0], '', $start, $limit);
                }else{
                    $ids = explode(',', $coupon_info['shop']);
                    $list = StoreProduct::selProductLimit(['status' => 0, 'is_del' => 0, 'id' => ['in', $ids]], '', $start, $limit);
                }
                foreach ($list as $k => $v){
                    if ($coupon_info['form'] == 0 ){
                        $list[$k]['quan_price'] = $v['price'] - $coupon_info['discount'] >= 0 ? sprintf("%01.2f", $v['price'] - $coupon_info['discount']) : 0.00;
                    }else{
                        $list[$k]['quan_price'] = sprintf("%01.2f", $v['price'] * $coupon_info['discount'] / 10);
                    }
                }
                successCode(compact('coupon_info', 'list'));
                break;
            case 8:
                $ids = explode(',', $shop);
                $list = StoreProduct::selProductLimit(['id' => ['in', $ids], 'status' => 0, 'is_del' => 0], '', $start, $limit);
                successCode(compact('list'));
                break;
        }
    }
}